/**
 * Created with JetBrains PhpStorm.
 * User: cgp
 * Date: 13-4-9
 * Time: 下午6:08
 * To change this template use File | Settings | File Templates.
 */
var baseUrl = 'call/jh_prod.php';
jQuery(document).ready(function($){
    $("input[name='s_title']").placeholder();
    $("input[name='chkall']").bind('click',function(){
        ckhall($(this));
    });
    $("table.ticket_list").on('click',"a.set_state",function(){
        var pid = $(this).attr('data-pid'),
            status=parseInt($(this).attr('data-state'));
        if(!confirm('您确定要执行'+pub.ticketOpState[status]+'操作吗？')) return;
        $.post(baseUrl,{action:'SetProdStatus',ids:pid,status:status},function(res){
            if(res.status=='ok') {
                $("tr#tr_"+pid).remove();
            } else {
                alert(res.msg);
            }
        },'json');
    });
    $("table").on('click', 'a.wSales', function(){
        var elem=$(this),
        rp = {
            action:'CountSale',
            tid   : $(this).parent().siblings('td.id').attr('data-tid')
        };
        $.get(baseUrl, rp, function(count){
            elem.parent().text(count);
        });
    });
    $("table").on('click', 'a.more', function(){
        if($(this).hasClass('opened')) {
            $(this).removeClass('opened')
                .find('i').removeClass('up_arrow');
            $(this).parents('tr').siblings('tr.more').addClass('hidden');
        } else {
            $(this).addClass('opened')
                .find('i').addClass('up_arrow');
            $(this).parents('tr').siblings('tr.more').removeClass('hidden');
        }
    });
    //产品状态批量配置
//    $("button[name='mulSet']").bind('click',function(){
//        if(!confirm('您确定要执行此操作吗？')) return;
//        var postId = getChkdIds();
//        if(! postId.length) return;
//        $.post('jh/jh.php',{todo:'mutiStatusSet',ids:postId,status:$(this).attr('data-state')},function(res){
//            alert(res.msg);
//            if(res.errcode==1000) {
//                location.reload();
//            }
//        },'json');
//    });

    $("table#tb_prod_list").on('click','a.storage_set',function(){
        var that = $(this);
        easyDialog.open({
            container : {
                header : '总库存设置',
                content : " 请输入库存量：<input type='text' id='storage_num' />",
                yesFn: function(){
                    var s = $("#storage_num").val(),
                        p = that.parents('tr').attr('id');
                    if(s==='') {
                        alert('请输入库存量！');
                        return;
                    }
                    p = Number(p.substr(3));
                    s = Number(s);
                        //console.log(p, s);
                    $.post(baseUrl,{todo:'SetStorage',p:p,s:s})
                        .done(function(res){
                            if(res=='ok'){
                                easyDialog.open({
                                    container : {
                                        content : '更新总库存量成功！'
                                    },
                                    autoClose : 2000
                                });
                                that.parent().siblings('td.storage_td').text(s);
                            } else {
                                alert(res);
                            }
                        });
                },
                noFn : true
            }
        });
    });
    //销售范围设置
    var state_list = ['不限','下架','仅零售','仅分销','仅直属下级','仅所有者'],
        state_list_l = ['<span class="green">不限</span>','<span class="orangered">下架</span>','仅零售','仅分销','仅直属下级','仅所有者'];
    //门票状态配置
    $("table#tb_prod_list").on('click','a.appto',function(){
        var pid = $(this).attr('data-pid'),that=$(this);
        var content = '产品销售范围选择：<select id="p_status">';
        content += '<option value="">--请选择--</option>';
        content += '<option value="0">不限</option>';
        content += '<option value="2">仅零售</option>';
        content += '<option value="3">仅分销销售</option>';
        content += '<option value="4">仅直属下级销售</option>';
        content += '<option value="5">仅所有者销售</option>';
        content += '</select>';
       // content += '<p style="margin:10px 0 -10px 0;background-color: #fef1eb;border:1px solid #ff7d44;padding:4px;">说明：该设置涉及到产品的销售状态，请认真核对产品信息后执行此操作</p>';
        var postFn = function(){
            var p_status = $("select#p_status").val();
            if(p_status=='') return;
            $.post(baseUrl,{action:'SetProdState',pid:pid,p_status:p_status},function(res){
                if(res.errcode==1000) {
                    alert('设置成功!');
                    that.parents('tr').find('span.app2state').html(state_list_l[p_status]);
                    //location.reload();
                } else {
                    alert(res.msg);
                }
            },'json');
        };
        easyDialog.open({
            container : {
                header : '产品销售范围设置',
                content : content,
                yesFn: postFn,
                noFn : true
            }
        });
    });
    $("button#saveSorts").bind('click',function(){
        var sortNum = parseInt($("input#sortsNum").val()),
            postId = getChkdIds('array');
        $.ajax({
            url:'call/jh_front.php',
            data:{action:'SetTicketPx',ids:postId,sort:sortNum},
            type:'post',
            beforeSend:function(){
                $("button#saveSorts").attr('disabled','disabled');
            },
            success:function(res){
                if(res==1000) {
                    alert('设置推荐度成功！');
                    for(var i= 0,len=postId.length;i<len;i++){
                        $("tr#tr_"+postId[i]).find("td.tjd").text(sortNum);
                    }
                } else {
                    alert('发生错误，设置失败');
                }
            },
            complete:function(){
                $("button#saveSorts").removeAttr('disabled');
            }
        });
    });
    $("input[name='rstate']").click(function(){
        $("form").submit();
    });
    $("input.sub").keydown(function(event){
        if(event.keyCode==13) {
            $("form").submit();
        }
    });

    $("table#tb_prod_list").on('click','a.prod_copy',function(event){
        event.preventDefault();
        var _url = $(this).attr('href');
        easyDialog.open({
            container : {
                header : '请输入新的产品名称',
                content : "<input type='text' id='c_title' />",
                yesFn: function(){
                    location.href = _url +'&c_title=' + encodeURIComponent($("#c_title").val());
                },
                noFn : true
            }
        });
        return false;
    });

    $("a.set_ls").click(function(){
        var state = $(this).attr('data-state'), lid = $(this).parent().attr('data-sid'),
            state_list = ['','设置产品为“上架”状态吗？\n产品上架后需手动设置其所属票类的状态',
                '设置产品为“下架”状态吗？\n产品下架后其所属票类也会一同下架','删除该产品？\n产品删除后其所属票类也会一同删除'];
        if(!confirm("您确定要"+state_list[state])) {
            return false;
        }
        var action ='SetSceneryState',errMsg = '发出未知错误，请联系网站工作人员';
		if($(this).attr('data-type')=='F' && state==1){// 套票上架
			action = 'SetPackState';
			errMsg = '套票关联门票错误，请检查所有门票是否上架，提前天数，有效期是否冲突';
		}
		$.post(baseUrl,{action:action,'lid':lid, state:state},function(res){
			if(res==1000) {
				alert('操作成功！');
				$("#box_"+lid).remove();
				
			//	$("span.total_page").text();
			} else {
				alert(errMsg);
			}
		});
        return false;
    });
    //产品审核
    $(".box").on('click',"span.examine_btn",function(e){
        var id = $(this).attr('data-id');
        var pid = $(this).attr('data-pid');
        var state = $(this).attr('data-state');
		if(state=="1"){
        if(!confirm('您确定要执行审核操作吗？')) return;
        $.post("http://www.12301.cc/module/qkxproject/call/jh_prod.php",{action:'SetVerifyStatus',id:id,state:state},function(res){
            if(res.status=="success") {
                $("#box_"+id).find(".set_examine_c").html("已审核");
                $("#box_"+id).find(".set_examine_c").css("background-color","#3dba3f");
				$("#box_"+id).find(".set_examine_c").attr("data-state","0");
            } else {
                alert(res.msg);
            }
        },'json');
		}
		else{
			if(!confirm('您确定要执行取消审核操作吗？')) return;
			$.post("http://www.12301.cc/module/qkxproject/call/jh_prod.php",{action:'SetVerifyStatus',id:id,state:state},function(res){
				if(res.status=="success") {
					$("#box_"+id).find(".set_examine_c").html("未审核");
					$("#box_"+id).find(".set_examine_c").css("background-color","#f07845");
					$("#box_"+id).find(".set_examine_c").attr("data-state","1");
				} else {
					alert(res.msg);
				}
			},'json');
			
		}
    });
	 $(".examine_btn").each(function(){
			var state = $(this).attr('data-state');
			if(state=="0"){ 
				$(this).css("background-color","#3dba3f");
			}
		});
   /* $("a.set_sh").click(function(){
        var state = $(this).attr('data-state'), lid = $(this).parent().attr('data-sid'),
            state_list = ['','设置产品为“审核通过”吗？\n',
                '设置产品为“未通过审核”吗？\n'];

        if(!confirm("您确定要"+state_list[state])) {
            return false;
        }
        var action ='SetVerifyStatus',errMsg = '发出未知错误，请联系网站工作人员';
        $.post(baseUrl,{action:action,'lid':lid, state:state},function(res){
            if(res.status=="success") {
                alert('操作成功！');
                $("#box_"+lid).remove();
                //	$("span.total_page").text();
            } else {
                alert(errMsg);
            }
        });
        return false;
    });*/


    $("#filter_ptype").on('click','a',function(){
        var pt = $(this).attr('data-pt');
        if(pt=='ALL'){
            $("tbody").show();
        } else {
            $("tbody").hide();
            $("tbody.tbd_pt_"+pt).show();
        }
    });
    $(".box").on('click', 'a.sync', function(){
        var params = {},
            action = $(this).data('action'),
            action_msg = {
                sync_land:'您确定要将该产品同步到先行平台吗?\n同步产品也会同步票类',
                sync_ticket:'您确定要同步该票吗',
                cancel_sync_land:'您确定要取消同步吗?\n取消同步后将在票付通平台独立运营，无法再次同步。'
            };
        if (!confirm(action_msg[action])) {
            return;
        }
        switch (action) {
            case 'sync_land':
                params = {lid:$(this).data('lid'), action:'sync_land'};
                break;
            case 'sync_ticket':
                params = {tid:$(this).data('tid'), action:'sync_ticket'};
                break;
            case 'cancel_sync_land':
                params = {lid:$(this).data('lid'), action:'cancel_sync'};
                break;
        }
        //return false;
        $.getJSON('/module/sync/index.php', params)
            .done(function(ret){
                if (ret.code==100) {
                    alert('您的账号还未绑定，点确定后页面将跳转到账号绑定页');
                    window.location.href="sync_auth.html";
                } else if (ret.status=='ok') {
                    alert(ret.msg);
                    //window.location.reload();
                } else {
                    alert(ret.msg);
                }
            });
    });
	
	//计算最低价
	$("#boxContainer").children(".box").each(function(){
		var box = $(this);
		var table = box.children("table.ticket_list");
		var gprice = box.find(".gprice");
		var minprice = 100000;
		if(gprice.length==0) return true;
		gprice.each(function(index){
			var price = $(this);
			var pt = price.text();
			var dollar = price.find(".dollar");
			if(dollar.length==0) return true;
			pt = pt.substring(1);
			if(pt<=minprice) minprice = pt;
			
		})
		box.find(".detail strong.minprice").text(minprice);
	})
	
	
});










